from flask import Blueprint, render_template
from urllib.parse import urlencode, urlparse, parse_qs
import requests
import json

music_bp = Blueprint('music', __name__)

@music_bp.route("/")
def index():
    return render_template("music/music.html")

@music_bp.route("/get_url/<string:song_id>")
def get_url(song_id):

    headers = {"Content-Type":"application/json","Accept":"*/*","Sec-Fetch-Site":"same-origin","Accept-Language":"en-US,en;q=0.9","Accept-Encoding":"gzip, deflate, br","Sec-Fetch-Mode":"cors","Origin":"https://wyapi.toubiec.cn","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.1 Safari/605.1.15","Referer":"https://wyapi.toubiec.cn/","Content-Length":"37","Sec-Fetch-Dest":"empty","Cookie":"server_name_session=460835dc0fd1342b765a6400845d873b; hasSeenWelcome=true","Priority":"u=3, i"}

    def post_data_with_timeout(url, data=None):
        """
        Performs a POST request with a timeout.

        Args:
            url (str): The URL to post the data to.
            data (dict, optional): The data payload to send. Defaults to None.

        Returns:
            requests.Response: The response object from the server.
        """
        # 2分钟的超时时间 (120000ms / 1000 = 120s)
        timeout_seconds = 120

        # requests.post() 会自动设置 Content-Type 为 application/json
        # 并且将字典自动转换为 JSON 字符串
        try:
            response = requests.post(
                url,
                json=data,
                timeout=timeout_seconds,
                headers=headers
            )
            response.raise_for_status()  # 如果请求失败（非2xx），则抛出异常
            return response
        except requests.exceptions.RequestException as e:
            #print(f"Request failed: {e}")
            return None


    url = "https://wyapi.toubiec.cn/api/music/url"
    payload = {"id": str(song_id), "level":"lossless"}

    # 发送请求
    response = post_data_with_timeout(url, payload)

    if response:
        response_data = response.json()
        # Check if the response has the expected structure
        if "data" in response_data and len(response_data["data"]) > 0 and "url" in response_data["data"][0]:
            if response_data["data"][0]["url"]:
                return response_data["data"][0]['url']
    
    # Return an empty response if no URL is found
    return "", 204  # No Content status code


@music_bp.route("/get_id/<string:song_name>")
def get_id(song_name):

    headers = {"Accept": "*/*", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-US,en;q=0.9",
                "Priority": "u=3, i",
                "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin",
               "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.1 Safari/605.1.15"}

    try:
        rsp = requests.get(f"https://apis.netstart.cn/music/search?keywords={song_name}", headers=headers).text
        data = json.loads(rsp)
        
        # Check the structure of the response and extract songs
        if "result" in data and "songs" in data["result"]:
            return {"songs": data["result"]["songs"]}
        elif "result" in data and "songCount" in data["result"] and "songs" in data["result"]:
            return {"songs": data["result"]["songs"]}
        else:
            # Return an empty list if no songs found
            return {"songs": []}
    except Exception as e:
        print(f"Error in get_id: {e}")
        return {"songs": []}


@music_bp.route("/get_id_from_link/<string:url>")
def get_id_from_link(url):
    query_string = urlparse(url).query

    parameters = parse_qs(query_string)

    q = parameters.get('id', [''])[0]

    return q